package com.soft.base.misc;

import com.google.common.base.Objects;
import com.soft.base.util.Md5Util;
import com.soft.base.util.Md5Util;
import com.xiaoleilu.hutool.bean.BeanUtil;

import java.util.Map;
import java.util.TreeMap;

/**
 * class
 *
 * @author user
 * @date 2020/06/05
 */
public class BasicSigner {

    public static Boolean validTimestampRange(Long timestamp) {
        long current = System.currentTimeMillis() / 1000L;
        long gap = 1800L;
        return timestamp > current - gap && timestamp < current + gap;
    }

    public static class Builder {
        private Map<String, Object> map = new TreeMap<String, Object>();

        public Builder put(String key, String value) {
            map.put(key, value);
            return this;
        }

        public Builder put(String key, Long value) {
            map.put(key, value);
            return this;
        }

        public Builder put(Map<String, String> param) {
            map.putAll(param);
            return this;
        }

        public Builder put(Object bean) {
            if (BeanUtil.isBean(bean.getClass())) {
                Map<String, Object> map = BeanUtil.beanToMap(bean);
                map.remove("sign");
                this.map.putAll(map);
            }
            return this;
        }

        public String build(String appSecret, String keyName) {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append('&');
            }
            sb.append(keyName).append("=").append(appSecret);
            return Md5Util.hexString(sb.toString());
        }

        public String build(String appSecret) {
            return build(appSecret, "appSecret");
        }

        public Boolean buildAndValid(String sign, String appSecret, String keyName) {
            return Objects.equal(sign, build(appSecret, keyName));
        }

        public Boolean buildAndValid(String sign, String appSecret) {
            return Objects.equal(sign, build(appSecret));
        }
    }

    public static Builder builder() {
        return new Builder();
    }

    public static void main(String[] args) {
        System.out.println(
                BasicSigner.builder()
                        .put("foo", "测试")
                        .put("bar", "value")
                        .build("test-app-secret")
        );
    }
}
